package com.cskaoyan.service;


import com.cskaoyan.bean.bo.WxOrderSubmitBO;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.cskaoyan.bean.bo.WxOrderCommentBo;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author zhuqiushi
 * @since 2022/09/09 21:42
 */
@Service
public class WxOrderServiceImpl implements WxOrderService{
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Override
    public WXOrderListVo getWXOrderList(Integer showType, Integer page, Integer limit, Integer userId) {
        WXOrderListVo listVo = new WXOrderListVo();

        Short orderStatus = null;
        if (showType == 1) {
            //待付款
            orderStatus = 101;
        } else if (showType == 2) {
            //待发货
            orderStatus = 201;
        } else if (showType == 3) {
            //待收货
            orderStatus = 301;
        } else if (showType == 4) {
            //待评价
            orderStatus = 401;
        }

        //查询订单
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.setOrderByClause("update_time desc");
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        if (orderStatus != null) {
            criteria.andOrderStatusEqualTo(orderStatus);
        }
        criteria.andDeletedEqualTo(false);
        PageHelper.startPage(page, limit);
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        PageInfo pageInfo = new PageInfo(marketOrders);
        listVo.setPages(pageInfo.getPages());
        listVo.setTotal((int) pageInfo.getTotal());
        listVo.setPage(page);
        listVo.setLimit(limit);

        for (MarketOrder marketOrder : marketOrders) {
            //查询订单对应的商品表
            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria criteriaGoods = marketOrderGoodsExample.createCriteria();
            criteriaGoods.andDeletedEqualTo(false);
            criteriaGoods.andOrderIdEqualTo(marketOrder.getId());
            List<MarketOrderGoods> marketOrderGoodsList = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

            listVo.setListEntity(marketOrder, marketOrderGoodsList);
        }


        return listVo;
    }

    @Override
    public BaseRespVo selectMessageById(Integer orderId) {
        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();
        WxOrderDetailHandleOptionVo detailHandleOptionVo = new WxOrderDetailHandleOptionVo();
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            wxOrderDetailVo.copyOrderGoods(marketOrderGood);
        }
        //cancel 暂定为系统取消
        if (marketOrder.getOrderStatus() == 103) {
            detailHandleOptionVo.setCancel(true);
        } else {
            detailHandleOptionVo.setCancel(false);
        }
        //confirm 确认收获 402
        if (marketOrder.getOrderStatus() == 301) {
            detailHandleOptionVo.setConfirm(true);
        } else {
            detailHandleOptionVo.setConfirm(false);
        }

        //rebuy
        /*MarketOrderGoodsExample goodsExample = new MarketOrderGoodsExample();
        List<MarketOrderGoods> marketOrderGoods1 = marketOrderGoodsMapper.selectByExample(goodsExample);
        for (MarketOrderGoods orderGoods : marketOrderGoods1) {
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                if (marketOrderGood.getGoodsName().equals(orderGoods.getGoodsName())) {
                    detailHandleOptionVo.setRebuy(true);
                }
            }
        }*/
        detailHandleOptionVo.setRebuy(true);

        //pay
        if (marketOrder.getOrderStatus() == 201) {
            detailHandleOptionVo.setPay(true);
        } else {
            detailHandleOptionVo.setPay(false);
        }
        //comment
        if (marketOrder.getOrderStatus() == 401) {
            detailHandleOptionVo.setComment(true);
        } else {
            detailHandleOptionVo.setComment(false);
        }
        //delete
        detailHandleOptionVo.setDelete(true);

        //aftersale
        if (marketOrder.getAftersaleStatus() == 0) {
            detailHandleOptionVo.setAftersale(false);
        } else {
            detailHandleOptionVo.setAftersale(true);
        }

        //refund
        if (marketOrder.getOrderStatus() == 201) {
            detailHandleOptionVo.setRefund(true);
        } else {
            detailHandleOptionVo.setRefund(false);
        }

        if (marketOrder.getOrderStatus() == 201) {
            detailHandleOptionVo.setRefund(true);
            detailHandleOptionVo.setAftersale(false);
            detailHandleOptionVo.setDelete(false);
            detailHandleOptionVo.setComment(false);
            detailHandleOptionVo.setPay(false);
            detailHandleOptionVo.setRebuy(false);
            detailHandleOptionVo.setConfirm(false);
            detailHandleOptionVo.setCancel(false);
        }


        wxOrderDetailVo.copyOrderInfo(marketOrder, detailHandleOptionVo);
        String string = new String();
        Short orderStatus = marketOrder.getOrderStatus();
        switch (orderStatus) {
            case 101:
                string = "未付款";
                break;
            case 102:
                string = "用户取消";
                break;
            case 103:
                string = "系统取消";
                break;
            case 201:
                string = "已付款";
                break;
            case 202:
                string = "申请退款";
                break;
            case 203:
                string = "已退款";
                break;
            case 301:
                string = "已发货";
                break;
            case 401:
                string = "用户收货";
                break;
            case 402:
                string = "系统收货";
                break;
        }
        wxOrderDetailVo.getOrderInfo().setOrderStatusText(string);

        BaseRespVo baseRespVo = BaseRespVo.ok(wxOrderDetailVo);
        return baseRespVo;
    }

    @Override
    public BaseRespVo insertMessage(WxOrderCommentBo commentBo,Integer id) {
        MarketComment marketComment = new MarketComment();
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(commentBo.getOrderGoodsId());
        marketComment.setValueId(marketOrderGoods.getGoodsId());
        Byte type = 0;
        marketComment.setType(type);
        marketComment.setUserId(id);
        BeanUtils.copyProperties(commentBo, marketComment);
        int insert = marketCommentMapper.insert(marketComment);

        //orderGoods表中更改comment状态
        marketOrderGoods.setComment(marketComment.getId());
        marketOrderGoodsMapper.updateByPrimaryKeySelective(marketOrderGoods);
        if (insert == 1) {
            //更改订单表的待评论订单商品数量
            Integer orderId = marketOrderGoods.getOrderId();
            //查询订单表内待评价商品数量
            MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
            short comments = marketOrder.getComments();
            if(comments>1){
                comments= (short) (comments-1);
                marketOrder.setComments(comments);
            }else {
                marketOrder.setComments((short) 0);
                marketOrder.setOrderStatus((short) 402);
            }
            //更新订单表待评价商品数量
            marketOrderMapper.updateByPrimaryKey(marketOrder);

            return BaseRespVo.ok();
        } else {
            return BaseRespVo.invalidData();
        }
    }

    @Transactional
    @Override
    public int confirm(Integer orderId) {
        Date date = new Date(System.currentTimeMillis());
        //对order表进行更改
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 401);
        marketOrder.setConfirmTime(date);
        marketOrder.setUpdateTime(date);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        //对order-goods表进行修改该为可评价状态
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria()
                .andOrderIdEqualTo(orderId);
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setUpdateTime(date);
        marketOrderGoods.setComment(0);
        marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods, marketOrderGoodsExample);
        return 0;
    }

    @Override
    public WxOrderGoodsVO goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria()
                .andOrderIdEqualTo(orderId)
                .andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        WxOrderGoodsVO wxOrderGoodsVO = new WxOrderGoodsVO();
        if (marketOrderGoods.size() == 1) {
            BeanUtils.copyProperties(marketOrderGoods.get(0),wxOrderGoodsVO);
        }
        if(marketOrderGoods.size()>1){
            BeanUtils.copyProperties(marketOrderGoods.get(0),wxOrderGoodsVO);
        }
        return wxOrderGoodsVO;
    }

    @Override
    public void orderRefund(Integer orderId) {
        //通过id更新order表中 statusId为202 和updateTime
        short statusId = 202;

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.createCriteria().andIdEqualTo(orderId);

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(statusId);
        marketOrder.setUpdateTime(new Date(System.currentTimeMillis()));

        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }

    @Override
    public void orderDelete(Integer orderId) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.createCriteria().andIdEqualTo(orderId);

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUpdateTime(new Date(System.currentTimeMillis()));
        marketOrder.setDeleted(true);

        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }


    @Override
    public WxOrderSubmitVO submit(WxOrderSubmitBO wxOrderSubmitBO, MarketUser user) {
        Date date = new Date(System.currentTimeMillis());
        Integer couponId = wxOrderSubmitBO.getCouponId();
        //首先操作order表
        MarketOrder marketOrder = new MarketOrder();
        //再查address
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderSubmitBO.getAddressId());
        marketOrder.setMobile(marketAddress.getTel());
        marketOrder.setAddress(marketAddress.getAddressDetail());
        marketOrder.setConsignee(marketAddress.getName());
        //首先完成默认值的赋值
        marketOrder.setUserId(user.getId());
        marketOrder.setOrderStatus((short) 201);
        marketOrder.setAddTime(date);
        marketOrder.setUpdateTime(date);
        marketOrder.setDeleted(false);
        Long orderSn = date.getTime();
        marketOrder.setOrderSn(orderSn.toString());
        if (!StringUtil.isEmpty(wxOrderSubmitBO.getMessage())) {
            marketOrder.setMessage(wxOrderSubmitBO.getMessage());
        }
        BigDecimal temple = new BigDecimal(0);
        marketOrder.setGoodsPrice(temple);
        marketOrder.setFreightPrice(temple);
        marketOrder.setCouponPrice(temple);
        marketOrder.setIntegralPrice(temple);
        marketOrder.setGrouponPrice(temple);
        marketOrder.setOrderPrice(temple);
        marketOrder.setActualPrice(temple);
        //默认值搞完直接插入
        marketOrderMapper.insertSelective(marketOrder);
        //根据cartId去cart表查
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria
                .andDeletedEqualTo(false)
                .andCheckedEqualTo(true);
        if (wxOrderSubmitBO.getCartId() != null && wxOrderSubmitBO.getCartId() != 0) {
            criteria.andIdEqualTo(wxOrderSubmitBO.getCartId());
        }
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        BigDecimal goodsTotalPrice = new BigDecimal(0);
        MarketCart templeCart = new MarketCart();
        for (MarketCart marketCart : marketCarts) {
            //在这里基本完整所有需要插入表数据的查询
            Double number = marketCart.getNumber().doubleValue();
            Double price = marketCart.getPrice().doubleValue();
            goodsTotalPrice = BigDecimal.valueOf(goodsTotalPrice.doubleValue() + (price * number));
            //在这里插入ordergoods
            MarketOrderGoods target = new MarketOrderGoods();
            BeanUtils.copyProperties(marketCart, target);
            target.setId(null);
            target.setOrderId(marketOrder.getId());
            target.setComment(0);
            target.setAddTime(date);
            target.setUpdateTime(date);
            marketOrderGoodsMapper.insertSelective(target);
            //再对所有的cart改为已删除
            templeCart.setId(marketCart.getId());
            templeCart.setDeleted(true);
            marketCartMapper.updateByPrimaryKeySelective(templeCart);
        }
        //通过ID查找优惠券表
        BigDecimal couponPrice = new BigDecimal(0);
        MarketCoupon marketCoupon = null;
        if (couponId != 0) {
            marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
            couponPrice = marketCoupon.getDiscount();
            //这里把优惠券改为已使用
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setStatus((short) 1);
            marketCouponUser.setId(wxOrderSubmitBO.getUserCouponId());
            marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);

        }else if (couponId == 0){
            couponPrice = BigDecimal.valueOf(0);
        }
        //计算运费freightPrice
        //免运费的最小值
        MarketSystem marketSystem = marketSystemMapper.selectByPrimaryKey(6);
        String freightMin = marketSystem.getKeyValue();

        //运费价钱
        MarketSystem marketSystem1 = marketSystemMapper.selectByPrimaryKey(8);
        String freight = marketSystem1.getKeyValue();

        BigDecimal freightPrice = new BigDecimal(0);
        if (goodsTotalPrice.doubleValue() < Double.valueOf(freightMin)){
            freightPrice = BigDecimal.valueOf(Double.valueOf(freight));
        }

        //计算得到actualPrice
        BigDecimal actualPrice = new BigDecimal(0);
        actualPrice =BigDecimal.valueOf(goodsTotalPrice.doubleValue() - couponPrice.doubleValue() + freightPrice.doubleValue());
        BigDecimal orderPrice = actualPrice;
        marketOrder.setGoodsPrice(goodsTotalPrice);
        marketOrder.setFreightPrice(freightPrice);
        marketOrder.setCouponPrice(couponPrice);
        marketOrder.setOrderPrice(orderPrice);
        marketOrder.setActualPrice(actualPrice);
        marketOrder.setComments((short) marketCarts.size());

        //再更改即可
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        WxOrderSubmitVO wxOrderSubmitVO = new WxOrderSubmitVO();
        wxOrderSubmitVO.setOrderId(marketOrder.getId());
        wxOrderSubmitVO.setGrouponLinkId(0);

        return wxOrderSubmitVO;
    }
}

